package web

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
)

// 查询子用户

func QueryWxUser(c *gin.Context) {
	DB := common.GetDB()
	telephone := c.PostForm("telephone")
	companyTelephone := c.PostForm("companyPhone")
	pageSize, _ := strconv.Atoi(c.PostForm("pageSize"))
	pageIndex, _ := strconv.Atoi(c.PostForm("pageIndex"))

	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	if pageIndex <= 0 {
		pageIndex = 1
	}

	if isCompanyExits(DB, companyTelephone) {
		wxUser := make([]model.WxUser, 0)
		var total int
		if telephone != "" {
			DB.Where("company_phone = ?", companyTelephone).Where("telephone LIKE ?", "%"+telephone+"%").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&wxUser).Offset(-1).Limit(-1).Count(&total)
			response.Reponse(c, http.StatusOK, 200, gin.H{
				"data":     wxUser,
				"total":    total,
				"page":     pageIndex,
				"pageSize": pageSize,
			}, "获取成功")
			return
		} else {
			DB.Where("company_phone = ?", companyTelephone).Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&wxUser).Offset(-1).Limit(-1).Count(&total)
			response.Reponse(c, http.StatusOK, 200, gin.H{
				"data":     wxUser,
				"total":    total,
				"page":     pageIndex,
				"pageSize": pageSize,
			}, "获取成功")
			return
		}
		return
	} else {
		response.Reponse(c, http.StatusOK, 422, nil, "传入的公司手机号不存在")
		return
	}
}
